import sys
import os
import re

from importlib.machinery import SourceFileLoader

thisDir = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(os.path.join(thisDir, "pai"))
sys.path.append(os.path.join(thisDir, "..", "server"))
sys.path.append(os.path.join(thisDir, "..", "common"))

import EJOConst

from PAI import PAI
from EJOServerInitializer import EJOServerInitializer
from SessionManager import SessionManager
from EJOHandlerBase import EJOHandlerBase

import logging
logger = logging.getLogger(__name__)

class EJOApiInitializer(EJOServerInitializer):
    def __init__(self):
        logger.debug("[EJOApiInitializer.EJOApiInitializer]")
        super().__init__()

    def Initialize(self):
        logger.debug("[EJOApiInitializer.Initialize]")
        return self.__initAPI()

    def __initAPI(self):
        configPath = os.path.join(thisDir, "EJOApi.py")
        schemaDir = os.path.join(thisDir, "..", "schema")
        api = PAI(configPath, schemaDir)
        if not api:
            logger.error("PAI load failed")
            return False
        SessionManager().SetProperty(EJOConst.SESSION_PROPERTY_API, api)
        self.__initAPIHandler()
        return True

    def __initAPIHandler(self):
        handlers = {}
        handlerDir = os.path.join(thisDir, "..", "server", "handlers")
        for handlerFile in os.listdir(handlerDir):
            try:
                handlerPath = os.path.join(handlerDir, handlerFile)
                if os.path.isfile(handlerPath) and re.match("^[\\w]+\\.py$", handlerFile):
                    handlerName = handlerFile[0:-3]
                    handlerModule = SourceFileLoader(handlerName, handlerPath).load_module()
                    handler = getattr(handlerModule, handlerName)
                    if handler:
                        if issubclass(handler, EJOHandlerBase):
                            handlers[handlerName] = handler
                        else:
                            logger.error(f"Handler is not subclass of EJOHandlerBase: {handler}")
                    else:
                        logger.error(f"Handler is not loaded: {handlerFile}")
            except Exception as e:
                logger.error(f"Handler file loading exception: {handlerFile}")
                logger.error(e)
        SessionManager().SetProperty(EJOConst.SESSION_PROPERTY_API_HANDLER, handlers)
